// pages/detail/detail.js
const appConfig = require('../../config/config.js');
const http = require('../../utils/http.js');
const nav = require('../../utils/navigator.js');
const imageUtil = require('../../utils/util.js');
const tip = require('../../utils/tip.js');
const util = require('../../utils/util.js');

//获取应用实例
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        distance: 0, //距离
        currentUserId: '',
        floorId: null, //发帖人 取启事userid字段
        noticeId: null,
        noticeType: null,
        replyName: '有爱评论，给点鼓励吧~',
        replyUserId: null, //回复某一用户的id
        sourceId: null, //源留言id
        commentContent: '', //留言内容
        txtImg: '',
        txtPhone: '', //手机号码
        txtTitle: '', //标题
        txtName: '', //名字
        txtAddress: '', //详细地址
        txtDescription: '', //走失经过
        txtPetName: '',
        province: '',
        city: '',
        area: '',
        createDate: '',
        happendDate: '',
        gender: '',
        color: '',
        category: '',
        status: '', //启事状态
        videoPath: '',
        favoriteCnt: '',
        hasFavorite: false, //是否收藏
        isSelf: 0, //是否为本人发布 0 非本人 1 本人
        shareCnt: '',
        msgCnt: '',
        msgList: [],
        imgUrls: [], //原图
        s_imgUrls: [], //列表图片
        imagewidth: 0, //缩放后的宽
        imageheight: 0, //缩放后的高
        windowWidth: 0,
        windowHeight: 0,
        shareImgSrc: '',
        portrait_temp: 'https://wx.qlogo.cn/mmopen/vi_32/TjEsP1siaib6rNdcPGuwdeVusmMCYiacPA2RjehEkqdiaZHr9RM2oqqjbHoHcfjxmeU5v0eQ6IKMvVjW0EF0HsFhiaQ/132',
        qrcode: 'https://www.bootu.net/resources/uploads/qrcode.jpg', //小程序码图片
        scale: 1.6,
        showDialog: false
    },
    imageLoad: function (e) {
        var imageSize = imageUtil.imageUtil(e);
        this.setData({
            imagewidth: imageSize.imageWidth,
            imageheight: imageSize.imageHeight,
            scale: 1.6
        });
    },
    /** 	 
     * 预览图片	 
     */
    previewImage: function (e) {
        console.log(e)
        var current = e.currentTarget.dataset.src;
        wx.previewImage({
            current: current, // 当前显示图片的http链接		  	
            urls: this.data.imgUrls // 需要预览的图片http链接列表		
        })
    },
    /** 
     * 收藏按钮点击事件
     */
    bindFavoriteClick: function (e) {
        var that = this;
        //console.log(that.data.noticeId)
        wx.showLoading({
            title: '加载中，请稍后...',
        });
        http.post(appConfig.baseUrl + 'Notice/SaveFavorite', {
            NoticeId: that.data.noticeId,
            UserId: wx.getStorageSync('userId')
        }, function (res) {
            if (res) {
                console.log(res.data);
                wx.hideLoading(); //关闭加载动画
                if (res.data.Flag == true) {
                    that.setData({
                        hasFavorite: res.data.Content == "0" ? false : true,
                        favoriteCnt: res.data.Content == "0" ? parseInt(that.data.favoriteCnt - 1) : parseInt(that.data.favoriteCnt + 1)
                    });
                } else {
                    tip.showToast('抱歉，处理失败，请稍后再试！');
                }


            }
        }, function (res) {
            wx.hideLoading(); //关闭加载动画
            tip.showToast('系统繁忙，请稍后再试！');
        });
        // http.post(appConfig.baseUrl + 'Notice/GetWXACodeUnlimit', {
        //   Id: that.data.noticeId
        // }, function(res) {
        //   if (res) {
        //     console.log(res.data);
        //     wx.hideLoading(); //关闭加载动画
        //   }
        // }, function(res) {
        //   wx.hideLoading(); //关闭加载动画
        //   tip.showToast('系统繁忙，请稍后再试！');
        // });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

        console.log(wx.getStorageSync('userId'));
        //获取用户设备信息，屏幕宽度
        var that = this;
        wx.showShareMenu({
            // 要求小程序返回分享目标信息
            withShareTicket: true
        });
        wx.getSystemInfo({
            success: res => {
                console.log(res);
                that.setData({
                    windowWidth: res.screenWidth,
                    windowHeight: res.screenHeight,
                });
            }
        });

        wx.showLoading({
            title: '玩命加载中...',
        });

        console.log(options.noticeId);
        that.setData({
            noticeId: options.noticeId,
            //txtImg: app.globalData.userInfo == null ? '' : app.globalData.userInfo.avatarUrl
        });
        http.post(appConfig.baseUrl + 'Notice/GetNoticeDetail', {
            id: options.noticeId,
            UserId: wx.getStorageSync('userId')
        }, function (res) {
            if (res) {
                console.log(res.data);
                wx.hideLoading(); //关闭加载动画
                if (!res.data) {
                    tip.showToast('抱歉，未获取到该启事信息', 'none', function (res) {
                        setTimeout(function () {
                            nav.redirectTo("../index/index");
                        }, 2000);
                    });
                    return false;
                }
                var imgs = []; //详情图片
                var s_imgs = []; //列表图片
                if (res.data && res.data.FileList) {
                    for (var i = 0; i < res.data.FileList.length; i++) {
                        var names = res.data.FileList[i].Url.split(".");
                        var file_name = names[0] + "." + names[1] + "." + names[2];
                        var pfix = res.data.FileList[i].Url.split(".")[3];
                        imgs.push(res.data.FileList[i].Url);
                        s_imgs.push(file_name + "_m." + pfix);
                    }
                    //console.log(imgs, s_imgs)
                }
                console.log(res.data.UserId)
                that.setData({
                    currentUserId: wx.getStorageSync('userId'),
                    floorId: res.data.UserId,
                    noticeType: res.data.NoticeType,
                    createDate: res.data.CreateTimeName,
                    txtPhone: res.data.Telphone || "",
                    //txtTitle: res.data.Title,
                    txtImg: res.data.AvatarUrl,
                    txtName: res.data.NickName,
                    txtPetName: res.data.PetName,
                    txtAddress: res.data.Address,
                    txtDescription: res.data.Description,
                    province: res.data.ProviceName,
                    city: res.data.CityName,
                    area: res.data.AreaName,
                    gender: res.data.Gender == 0 ? "弟弟" : "妹妹",
                    color: getColorName(res.data.Color),
                    category: res.data.CategoryName,
                    status: res.data.Status,
                    happendDate: res.data.HappenTimeName,
                    favoriteCnt: res.data.FavoriteCnt,
                    shareCnt: res.data.ShareCnt,
                    msgCnt: res.data.MsgCnt,
                    msgList: res.data.MsgList,
                    videoPath: res.data.VideoPath == null ? "" : res.data.VideoPath,
                    imgUrls: imgs,
                    s_imgUrls: s_imgs,
                    hasFavorite: res.data.HasFavorite == 0 ? false : true,
                    isSelf: res.data.IsSelf,
                    distance: calculateDistance(res.data.Latitude, res.data.Longitude)
                    //res.data.FileList
                });
            }
        }, function (res) {

        });

        function getColorName(e) {
            var result = "";
            switch (e) {
                case 0:
                    result = "黑色";
                    break;
                case 1:
                    result = "白色";
                    break;
                case 2:
                    result = "灰色";
                    break;
                case 3:
                    result = "花色";
                    break;
                case 4:
                    result = "棕色";
                    break;
                case 5:
                    result = "黄色";
                    break;
                case 6:
                    result = "蓝灰";
                    break;
            }
            return result;
        }
        //距离计算
        function calculateDistance(lat, lon) {
            var that = this;
            var dis = 0;
            dis = util.getDistance(app.globalData.locationInfo.latitude, app.globalData.locationInfo.longitude, lat, lon);
            return dis;
        }
    },
    downloadimg: function (e) {
        var that = this;

        wx.showLoading({
            title: '加载中...'
        })
        //1. 请求后端API生成小程序码
        http.post(appConfig.baseUrl + 'Notice/GetWXPosterUrl', {
            noticeId: that.data.noticeId
        }, function (res) {
            if (res) {
                console.log(res.data);
                if (res.data.Flag == true) {
                    wx.hideLoading();
                    console.log(res.data.Content);
                    that.setData({ showDialog: true, shareImgSrc: res.data.Content });
                } else {
                    tip.showToast('抱歉，处理失败，请稍后再试！');
                }
            }
        }, function (res) {
            wx.hideLoading(); //关闭加载动画
            tip.showToast('系统繁忙，请稍后再试！');
        });

    },
    /**
     * 置顶
     */
    bindTopClick: function (e) {
        var that = this;
        http.post(appConfig.baseUrl + 'Notice/RefreshUpdateTime', {
            Id: that.data.noticeId,
            UserId: wx.getStorageSync('userId')
        }, function (res) {
            if (res) {
                console.log(res.data);

                if (res.data.Flag == true) {
                    tip.showToast('置顶成功，24小时内请勿重新提交');
                } else {
                    tip.showToast(res.data.CodeMsg);
                }

            }
        }, function (res) {
            tip.showToast('系统繁忙，请稍后再试！');
        });
    },
    /**
     * 留言文本框事件
     */
    bindCommentBlur: function (e) {
        this.setData({
            commentContent: e.detail.value,
        });
    },
    /**
     * 发表留言
     */
    bindMsgClick: function (e) {
        var that = this;
        var content = that.data.commentContent;
        if (content == null || content == '') {
            tip.showToast('至少输入一个留言，才能提交哦');
            return false;
        }
        http.post(appConfig.baseUrl + 'Notice/SendMsg', {
            ParentId: that.data.sourceId,
            UserId: wx.getStorageSync('userId'),
            NoticeId: that.data.noticeId,
            ReplyUserId: that.data.replyUserId,
            Content: that.data.commentContent
        }, function (res) {
            if (res) {
                console.log(res.data);
                if (res.data.Flag == true) {
                    that.setData({
                        msgList: res.data.Content,
                        commentContent: '',
                        replyName: "有爱评论，给点鼓励吧~",
                        replyUserId: null,
                        sourceId: null
                    });
                    tip.showToast('留言成功');
                    //刷新留言数量
                    http.post(appConfig.baseUrl + 'Notice/GetMsgCount', {
                        NoticeId: that.data.noticeId
                    }, function (res) {
                        console.log(res.data)
                        if (res.data.Flag == true) {
                            that.setData({ msgCnt: res.data.Content });
                        }
                    }, function (res) {
                        tip.showToast('系统繁忙，请稍后再试！');
                    });
                } else {
                    tip.showToast(res.data.CodeMsg);
                }

            }
        }, function (res) {
            tip.showToast('系统繁忙，请稍后再试！');
        });
    },
    /**
     * 留言内容点击事件
     */
    bindReplyClick: function (e) {
        var that = this;
        var name = e.currentTarget.dataset.name;
        var replyUserId = e.currentTarget.dataset.replyuserid;
        console.log(name + replyUserId);
        that.setData({
            replyName: "回复:" + name,
            replyUserId: replyUserId,
            sourceId: e.currentTarget.dataset.sourceid
        });

    },
    /**
     * 编辑按钮事件
     */
    bindEditClick: function (e) {
        var that = this;
        //console.log(that.data.noticeId)
        nav.navigateTo('../notice/notice', {
            noticeId: that.data.noticeId,
            noticeType: that.data.noticeType
        });
    },
    /**
     * 保存分享海报
     */
    btnSaveImg: function (e) {
        var that = this;
        wx.showLoading({
            title: '保存中...'
        })
        wx.downloadFile({
            url: that.data.shareImgSrc,
            success: function (res) {
                //图片保存到本地
                wx.saveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                    success: function (data) {
                        wx.hideLoading();
                        that.setData({
                            showDialog: false
                        });
                        wx.showModal({
                            title: '提示',
                            content: '您的推广海报已存入手机相册，赶快分享给好友吧',
                            showCancel: false,
                        })
                    },
                    fail: function (err) {
                        if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                            // 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
                            wx.showModal({
                                title: '提示',
                                content: '需要您授权保存相册',
                                showCancel: false,
                                success: modalSuccess => {
                                    wx.openSetting({
                                        success(settingdata) {
                                            console.log("settingdata", settingdata)
                                            if (settingdata.authSetting['scope.writePhotosAlbum']) {
                                                wx.showModal({
                                                    title: '提示',
                                                    content: '获取权限成功,再次点击图片即可保存',
                                                    showCancel: false,
                                                })
                                            } else {
                                                wx.showModal({
                                                    title: '提示',
                                                    content: '获取权限失败，将无法保存到相册哦~',
                                                    showCancel: false,
                                                })
                                            }
                                        },
                                        fail(failData) {
                                            console.log("failData", failData)
                                        },
                                        complete(finishData) {
                                            console.log("finishData", finishData)
                                        }
                                    })
                                }
                            })
                        }
                    },
                    complete(res) {
                        wx.hideLoading()
                    }
                })
            }
        });
    },
    btnCloseModal: function (e) {
        this.setData({
            showDialog: false
        });
    },
    /**
    * 控制 pop 的打开关闭
    * 该方法作用有2:
    * 1：点击弹窗以外的位置可消失弹窗
    * 2：用到弹出或者关闭弹窗的业务逻辑时都可调用
    */
    toggleDialog() {
        this.setData({
            showDialog: !this.data.showDialog
        });

    },
    btnMsgClick: function (e) {
        wx.requestSubscribeMessage({
            tmplIds: [appConfig.msgTemplate],
            success(res) {
                console.log(res);
                //var acceptTemplateIds = Object.keys(res).filter(key => res[key] === 'accept');
                console.log(res[appConfig.msgTemplate]);
                if (res[appConfig.msgTemplate] == "accept") {
                    //tip.showToast('订阅成功，寻TA将为您及时推送启事留言信息');

                    //推送消息
                    http.post(appConfig.baseUrl + 'Notice/WXSubscribeMessageSend', {
                        ReplyUserId: wx.getStorageSync('userId')
                    }, function (res) {
                        console.log(res.data)
                        if (res.data.Flag == true) {
                            wx.showModal({
                                title: '订阅成功',
                                content: '寻TA将为您及时推送启事留言信息，赶快参与留言讨论吧',
                                showCancel: false,
                            });
                        }
                    }, function (res) {
                        tip.showToast('系统繁忙，请稍后再试！');
                    });
                }
            }, fail(ret) {
                console.log(ret);
                tip.showToast('抱歉，订阅失败，请稍后再试');
            }
        })
    },
    /**
     * 订阅启事匹配推送
     * @param {*} e 
     */
    bindSubscribeNotice: function (e) {
        var that = this;
        app.subscribeAdapter(wx.getStorageSync('userId'), that.data.noticeId, () => { });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (e) {
        if (e.from === 'button') {

        }

        http.post(appConfig.baseUrl + 'Notice/GetNoticeFile', {
            Id: this.data.noticeId
        }, function (res) {

            if (res.data) {
            return {
                title: '转发',
                path: '/pages/detail/detail?noticeId=' + this.data.noticeId,
                imageUrl: res.data.Url,
                success: function (ret) {
                    console.log('分享分享成功', ret)
                    // 转发成功之后的回调
                    if (ret.errMsg == 'shareAppMessage:ok') {
                        http.post(appConfig.baseUrl + 'Notice/SaveShare', {
                            NoticeId: this.data.noticeId,
                            UserId: wx.getStorageSync('userId')
                        }, function (res1) {
                                console.log(res1.data)
                                if (res1.data.Flag == true) {
                                    tip.showToast('系统繁忙，请稍后再试！');
                            }
                        }, function (res1) {
                                tip.showToast('分享成功');
                        });
                    }
                    //可以获取群组信息
                    wx.getShareInfo({
                        shareTicket: shareTickets[0],
                        success: function (res) {
                            console.log(res)
                        }
                    })
                }
            }
        }
    
    }, function(res) {
        tip.showToast('系统繁忙，请稍后再试！');
    });

    
  }
})